var editor;
$(document).ready(function() {
	editor = ace.edit("editor");
	//editor.setTheme("ace/theme/textmate");
	var HtmlMode = require("ace/mode/html").Mode;
	editor.getSession().setMode(new HtmlMode());
	editor.renderer.setShowPrintMargin(false);
	editor.renderer.setStyle("font-size:50px;");
	editor.getSession().setUseWrapMode(true);
	editor.setSelectionStyle("text");
	var canon = require("pilot/canon");
	
    canon.addCommand({
        name: "p-tag",
        bindKey: {
            win: "Ctrl-P",
            mac: "Command-P",
            sender: "editor"
        },
        exec: function(env) {
        	wrap_with(env, '<p>\n', '\n</p>', 1, 0);
        }
    });
    
    canon.addCommand({
        name: "ul-tag",
        bindKey: {
            win: "Ctrl-U",
            mac: "Command-U",
            sender: "editor"
        },
        exec: function(env) {
        	wrap_with(env, '<ul>\n\t<li>', '</li>\n</ul>', 1, 1);
        }
    });
    canon.addCommand({
        name: "li-tag",
        bindKey: {
            win: "Ctrl-L",
            mac: "Command-L",
            sender: "editor"
        },
        exec: function(env) {
        	wrap_with(env, '<li>', '</li>', 0, 0);
        }
    });
    canon.addCommand({
        name: "note-tag",
        bindKey: {
            win: "Ctrl-Shift-P",
            mac: "Command-Shift-P",
            sender: "editor"
        },
        exec: function(env) {
        	wrap_with(env, '<p class="note">\n', '\n</p>', 1, 0);
        }
    });
 
    canon.addCommand({
        name: "shift-left",
        bindKey: {
            win: "Ctrl-Alt-Left",
            mac: "Command-Alt-Left",
            sender: "editor"
        },
        exec: function(env) {
        	shift_left(env)
        }
    });
})

var tab_width = 4;
function shift_left(env){
	var sel = env.editor.selection;
	var session = env.editor.session;
	
	range = sel.getRange();
	for(var i=sel.selectionLead.row;i<=sel.selectionAnchor.row;i++){
		var line = session.getLine(i);
		var shift_width = count_space(line);
		if(shift_width==0){
			continue;
		}
		if(shift_width > tab_width){
			shift_width = tab_width;
		}
	    range.start = {'row':i, 'column':0};
	    range.end = {'row':i, 'column':shift_width};
	    session.remove(range);
	}
	
}

function count_space(string){
	var c = 0;
	for(i=0;i<string.length;i++){
		if(string.charAt(i)!=' ' && string.charAt(i)!='\t'){
			break;
		}
		c++;
	}
	return c;
}

function wrap_with(env, prefix, suffix, br, tab){
	var range = env.editor.selection.getRange();
	var start = range.start;
	var end = range.end;
	var session = env.editor.session;
	session.insert(end, suffix);
	session.insert(start, prefix);
	end.row += br;
	if(env.editor.selection.isMultiLine()){
		end.column = end.column + tab*5;
	}else{
		end.column = end.column + prefix.length + tab*5;
	}
	
	range = {'start':end,'end':end};
	env.editor.selection.setSelectionRange(range, false);
}
















